package com.tnovoselec.android.mojevijesti.adapter;

import java.io.ObjectInputStream.GetField;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.tnovoselec.android.mojevijesti.async.GetNewsAsync;
import com.tnovoselec.android.mojevijesti.async.GetNewsAsync.NewsDownloadedListener;
import com.tnovoselec.android.mojevijesti.dto.ChannelDto;
import com.tnovoselec.android.mojevijesti.fragment.NewsFragment;

public class NewsFragmentAdapter extends FragmentPagerAdapter {

	private ChannelDto channel;
	private LinkedHashMap<String, String> items;
	private Iterator<String> iter;
	private List<NewsDownloadedListener> listeners = new ArrayList<GetNewsAsync.NewsDownloadedListener>();

	public NewsFragmentAdapter(FragmentManager fm, ChannelDto channel) {
		super(fm);
		this.channel = channel;
		items = (LinkedHashMap<String, String>) channel.getItems();
		
	}

	@Override
	public Fragment getItem(int position) {
		NewsFragment fragment = new NewsFragment();
		Bundle args = new Bundle();
//		args.putString("key", getTitle(position));
		args.putInt("key", position);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public int getCount() {
		return channel.getItems().size();
	}
	
	
	

	@Override
	public CharSequence getPageTitle(int position) {
		return getTitle(position);
	}
	
	private String getTitle(int position){
		iter = items.keySet().iterator();
		int i = 0;
		while (iter.hasNext()){
			String title = iter.next();
			if (i == position){
				return title;
			}
			i++;
		}
		return "";
	}
	
	public void registerListener(NewsDownloadedListener listener){
		this.listeners.add(listener);
	}

	public void unregisterListener(NewsDownloadedListener listener){
		this.listeners.remove(listener);
		
	}
	

}
